package com.ybkj.daijia.api.apirest.v4;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ybkj.daijia.OrderConfirmLocs;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.api.driver.transport.ResultTransport;
import com.ybkj.daijia.api.util.ErrorConstantV4;
import com.ybkj.daijia.cache.DriverCache;
import com.ybkj.daijia.cache.MyCacheManager;
import com.ybkj.daijia.cache.SmallLocationService;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.config.ZhuanApi;
import com.ybkj.daijia.server.event.model.OrderEmployHasPayEvent;
import com.ybkj.daijia.server.event.model.OrderPassengerHasPayEvent;
import com.ybkj.daijia.server.event.model.zhuan.SaveLocationEvent;
import com.ybkj.daijia.server.event.model.zhuan.ZhuanOrderAcceptEvent;
import com.ybkj.daijia.server.event.model.zhuan.ZhuanOrderConfirmEvent;
import com.ybkj.daijia.server.event.model.zhuan.ZhuanOrderCreateEvent;
import com.ybkj.daijia.server.event.model.zhuan.ZhuanOrderRunEvent;
import com.ybkj.daijia.server.mapper.AreaMapper;
import com.ybkj.daijia.server.mapper.OrderLocationManyMapper;
import com.ybkj.daijia.server.mc.Enterprise;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Area;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverRefuseRecord;
import com.ybkj.daijia.server.model.FirstOrderPassenger;
import com.ybkj.daijia.server.model.OrderLocation;
import com.ybkj.daijia.server.model.OrderLocationMany;
import com.ybkj.daijia.server.model.SmsTemplet;
import com.ybkj.daijia.server.model.SmsTemplet.SmsType;
import com.ybkj.daijia.server.sales.Coupon;
import com.ybkj.daijia.server.sales.CouponRule;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.CouponService;
import com.ybkj.daijia.server.service.DriverHelppayService;
import com.ybkj.daijia.server.service.DriverLoginService;
import com.ybkj.daijia.server.service.DriverRefuseRecordService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.FirstOrderPassengerService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.OrderLocationManyService;
import com.ybkj.daijia.server.service.SmsService;
import com.ybkj.daijia.server.service.SuperviceService;
import com.ybkj.daijia.server.service.WxBindService;
import com.ybkj.daijia.server.service.ZhuancheService;
import com.ybkj.daijia.server.zhuan.Order;
import com.ybkj.daijia.server.zhuan.Order.PayTypeDetails;
import com.ybkj.daijia.server.zhuan.OrderStatus;
import com.ybkj.daijia.server.zhuan.SelectPrice;
import com.ybkj.daijia.server.zhuan.SmallLocation;
import com.ybkj.daijia.serverUtils.SettingUtils;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller("ApiZhuancheProcessControllerV4")
@RequestMapping(value = "api/zhuanche/v4/")
@Slf4j
public class ZhuancheProcessController {


    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private ZhuancheService zhuancheService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private DriverService driverService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private WxBindService wxBindService;
    @Autowired
    private DriverRefuseRecordService driverRefuseRecordService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private OrderLocationManyService orderLocationManyService;
    @Autowired
    private FirstOrderPassengerService firstOrderPassengerService;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;
    @Autowired
    private SuperviceService superviceService;
    @Autowired
    private ZhuanApi zhuanApi;
    @Autowired
    private DriverHelppayService helppayService;

    /**
     * 快车订单结算 快车完成行程
     * 司机点击结算订单,完成该行程,开始计算费用,支付费用,结算订单的流程
     * @record zhyu
     * @param orderId
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @RequestMapping(value = "completeTaskData", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport completeTaskData(Long orderId, @RequestParam(required = false, value = "jsonLocFile") MultipartFile jsonLocFile) {

//        log.error("recv orderId:{}", orderId);

        if (null == orderId) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        Order order = zhuancheService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        if (!order.getStatus().equals(Order.ORDER_STATUS_ZHIXING) && !order.getStatus().equals(Order.ORDER_STATUS_ARRIVE_DISTANCE)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
        }

        Driver driver = driverService.findOne(order.getEmployId());
        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        Passenger passenger = memberService.findOnePassenger(order.getPassengerId());
        if (null == passenger) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PASSENGER_NOT_EXISTS);
        }
        SelectPrice selectPrice = null;
//        log.error("cache start--");
        OrderLocationMany orderLocationMany = new OrderLocationMany();
        OrderLocationMany orderLocation_dr_ca = new OrderLocationMany();
        OrderLocationMany orderLocation_pa = new OrderLocationMany();
        OrderLocationMany orderLocationMany_dr = new OrderLocationMany();
        orderLocationMany.setOrderId(orderId);
        orderLocation_dr_ca.setOrderId(orderId);
        orderLocation_pa.setOrderId(orderId);
        orderLocationMany_dr.setOrderId(orderId);
        orderLocationMany_dr.setOrderType(OrderLocation.OrderType.zhuanche_dr);
        orderLocation_dr_ca.setOrderType(OrderLocation.OrderType.zhuanche_dr_ca);
        orderLocation_pa.setOrderType(OrderLocation.OrderType.zhuanche_pa);
        orderLocationMany.setOrderType(OrderLocation.OrderType.zhuanche);
        try {
            //获取司机缓存,并设置旅程结束时间, 并且重新计算价格;
            DriverCache driverCache = cacheManager.getDriverCache(driver.getId());
//            String jsonLocs = OrderConfirmLocs.locs(jsonLocFile, driver.getId() + "-" + orderId + ".loc");
            if (driverCache != null) {
                if (driverCache.getOrderStatus() == Order.ORDER_STATUS_ZHIXING) {
                    String jsonLocs = OrderConfirmLocs.locs(jsonLocFile);
                    LinkedList<SmallLocation> smallLocations = null;
                    List<SmallLocation> passengerLocationList = null;
                    if (StringUtils.isNotBlank(jsonLocs)) {
                        smallLocations = new LinkedList<>(JSON.parseArray(jsonLocs, SmallLocation.class));
                    }

                    if (driverCache != null) {
                        selectPrice = driverCache.getSelectPrice();
                        selectPrice.setEndRun(System.currentTimeMillis());
                        passengerLocationList = driverCache.getPassengerLocationList();
                        List<SmallLocation> driverLocationList = driverCache.getDriverLocationList();

                        if (passengerLocationList != null && !passengerLocationList.isEmpty()) {
                            List<SmallLocation> copy = new ArrayList<>(passengerLocationList);
                            String jsonLocs_pa = JSON.toJSONString(copy);
                            orderLocation_pa.setOrderId(orderId);
                            orderLocation_pa.setOrderType(OrderLocation.OrderType.zhuanche_pa);
                            orderLocation_pa.setJsonLocs(jsonLocs_pa);
                        }

                        if (driverLocationList != null && !driverLocationList.isEmpty()) {
                            List<SmallLocation> copy = new ArrayList<>(driverLocationList);
                            String jsonLocs_pa = JSON.toJSONString(copy);
                            orderLocation_dr_ca.setOrderId(orderId);
                            orderLocation_dr_ca.setOrderType(OrderLocation.OrderType.zhuanche_dr_ca);
                            orderLocation_dr_ca.setJsonLocs(jsonLocs_pa);
                        }

//                        LinkedList<SmallLocation> combineSmallLocations = smallLocationService.combineSmallLocations(smallLocations, passengerLocationList);
//                        if (smallLocations != combineSmallLocations) {
//                            orderLocationMany_dr.setOrderId(orderId);
//                            orderLocationMany_dr.setOrderType(OrderLocation.OrderType.zhuanche_dr);
//                            orderLocationMany_dr.setJsonLocs(jsonLocs);
//                        }

                        if (smallLocations == null || smallLocations.size() < 2) {
                            SmallLocation mid = null;
                            if(null != smallLocations && 1 == smallLocations.size()){
                                mid = smallLocations.get(0);
                            }
                            smallLocations = new LinkedList<SmallLocation>();
                            SmallLocation start = new SmallLocation();
                            start.setLocDate(selectPrice.getStartRun());
                            start.setLongitude(order.getStartLng());
                            start.setLatitude(order.getStartLat());
                            SmallLocation end = new SmallLocation();
                            end.setLocDate(selectPrice.getEndRun());
                            end.setLongitude(order.getEndLng());
                            end.setLatitude(order.getEndLat());
                            smallLocations.add(start);
                            if (mid != null) {
                                smallLocations.add(end);
                            }
                            if (locationLogger.isInfoEnabled()) {
                                locationLogger.info("add start and end");
                            }
                        }

                        Double miles = smallLocationService.filterAndComputeMiles(smallLocations, orderId);
//                        log.error("miles compuite ok --");
                        List<SmallLocation> copy = new ArrayList<>(smallLocations);
                        String jsonLocs_com = JSON.toJSONString(copy);
                        orderLocationMany.setOrderId(orderId);
                        orderLocationMany.setOrderType(OrderLocation.OrderType.zhuanche);
                        orderLocationMany.setJsonLocs(jsonLocs_com);
                        selectPrice.setRunKilometers(miles / 1000);
                        smallLocationService.freshSelectPrice(selectPrice, driverCache, order);
                    }
                    Setting setting = settingUtils.get();
                    if (order.getStatus().equals(Order.ORDER_STATUS_ZHIXING)) {
                        ResultTransport resultTransport = zhuanApi.arriveDistination(orderId, driver.getName(), setting.getSecKey(), setting);
                        if (resultTransport.getCode() != 0) {
                            log.error("访问专车系统设置已到到目的地失败, orderId = {}", orderId);
                            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
                        }
                    }
//                    log.error("update order ok --");
                    driverCache.setOrderStatus(Order.ORDER_STATUS_ARRIVE_DISTANCE);
                    SaveLocationEvent event = new SaveLocationEvent(orderLocationMany, orderLocation_dr_ca, orderLocation_pa, orderLocationMany_dr);
                    applicationEventMulticaster.multicastEvent(event);
                    cacheManager.saveOrUpdateObj(driverCache);

                } else {
                    selectPrice = driverCache.getSelectPrice();
                }
            }
            ResultTransport instance = wrapperCompleteTaskResp(order, driver, passenger, selectPrice);
//            log.error("method ok --");
            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }


    private ResultTransport wrapperCompleteTaskResp(Order order, Driver driver, Passenger passenger, SelectPrice selectPrice) {
        Map<String, Object> map = new HashMap<String, Object>();
        if (selectPrice != null) {
            map.put("priceData", selectPrice);
        }
        map.put("orderId", order.getId());
        map.put("orderNumber", order.getOrderNo());
        map.put("orderType", "zhuanche");

        map.put("passengerPhone", passenger.getPhone());
        map.put("passengerName", passenger.getName());
        map.put("passengerType", passenger.getTypeStr());

        //等级
        map.put("passengerGrade", passenger.getGrade_name());

        Company orderCompany = companyService.findOne(order.getCompanyId());
        map.put("orderCompanyName", orderCompany.getAbbreviation());

        Company passengerCompany = companyService.findOne(passenger.getCompanyId());
        map.put("passengerCompanyName", passengerCompany.getAbbreviation());

        if (Passenger.TYPE_PASSENGER.equals(passenger.getType())) {
            map.put("overdraw", passenger.isAllowOverdraw());
            map.put("virtual", passenger.getDrawMoney().add(passenger.getNodrawMoney()).setScale(2, BigDecimal.ROUND_HALF_UP));
        } else if (Passenger.TYPE_ENTERPRISE.equals(passenger.getType())) {
            Enterprise enterprise = memberService.findOneEnterprise(passenger.getEnterprise_id());
            map.put("overdraw", enterprise.isAllowOverdraw());
            map.put("virtual", enterprise.getDrawMoney().add(enterprise.getNodrawMoney()).setScale(2, BigDecimal.ROUND_HALF_UP));
        }

        //优惠券
        if (null != order.getCouponId()) {
            Coupon coupon = couponService.findOne(order.getCouponId());
            if (null != coupon) {
                CouponRule couponRule = coupon.getCouponRule();
                if (couponRule.getType().equals(CouponRule.TYPE_DEDUCTION)) {
                    map.put("couponMoney", couponRule.getMoney());
                    map.put("coupon_type", CouponRule.TYPE_DEDUCTION);
                } else if (couponRule.getType().equals(CouponRule.TYPE_DISCOUNT)) {
                    map.put("discount", couponRule.getDiscount());
                    map.put("coupon_type", CouponRule.TYPE_DISCOUNT);
                }
            }
        }

        //预先支付
        BigDecimal preyMoney = BigDecimal.ZERO;
        if (null != order.getAlipayMoney() && order.getAlipayMoney().doubleValue() > 0) {
            preyMoney = order.getAlipayMoney();
        } else if (null != order.getWeixinMoney() && order.getWeixinMoney().doubleValue() > 0) {
            preyMoney = order.getWeixinMoney();
        } else if (null != order.getUnionpayMoney() && order.getUnionpayMoney().doubleValue() > 0) {
            preyMoney = order.getUnionpayMoney();
        } else if (null != order.getSignMoney() && order.getSignMoney().doubleValue() > 0) {
            preyMoney = order.getSignMoney();
        } else if (null != order.getBalanceMoney() && order.getBalanceMoney().doubleValue() > 0) {
            preyMoney = order.getBalanceMoney();
        }
        map.put("preyMoney", preyMoney.setScale(2, BigDecimal.ROUND_HALF_UP));

        //首单免费
        Long completeTimes = firstOrderPassengerService.selectAll(passenger.getId(), FirstOrderPassenger.FREE_ORDERTYPE_ZHUANCHE);
        if (completeTimes > 0) {
            map.put("firstFree", false);
        } else {
            map.put("firstFree", true);
        }

        map.put("employId", driver.getId());
        map.put("employName", driver.getName());
        map.put("employPhone", driver.getPhone());

        ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
        instance.setData(map);
        return instance;
    }

    @RequestMapping(value = "checkTask", method = RequestMethod.GET)
    public @ResponseBody
    ResultTransport checkTask(Long orderId) {

        if (null == orderId) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        Order order = zhuancheService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        try {

            boolean finished = false;
            if (order.getStatus().equals(Order.ORDER_STATUS_OK)) {
                finished = true;
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData(finished);
            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }

//    @RequestMapping(value = "confirmTask", method = RequestMethod.POST)
//    public @ResponseBody
//    ResultTransport confirmTask(
//            Long orderId,
//            BigDecimal realCash, BigDecimal guoluMoney, BigDecimal yuanchengMoney, BigDecimal otherMoney,
//            Double mileage, Integer waitedTime, Integer travelTime,
//            @RequestParam(required = false, value = "toPlace") String toPlace,
//            @RequestParam(required = false, value = "toPlaceLng") Double toPlaceLng,
//            @RequestParam(required = false, value = "toPlaceLat") Double toPlaceLat,
//            @RequestParam(required = false, value = "startPrice") BigDecimal startPrice,
//            @RequestParam(required = false, value = "mileagePrice") BigDecimal mileagePrice,
//            @RequestParam(required = false, value = "runTimePrice") BigDecimal runTimePrice,
//            @RequestParam(required = false, value = "waitPrice") BigDecimal waitPrice,
//            @RequestParam(required = false, value = "memo") String memo,
//            @RequestParam(required = false, value = "jsonLocs") String jsonLocs) {
//
//        return confirmTaskFunction(orderId, realCash, guoluMoney, yuanchengMoney, otherMoney, mileage, waitedTime, travelTime,
//                toPlace, toPlaceLng, toPlaceLat, startPrice, mileagePrice, runTimePrice, waitPrice, memo, null, null, jsonLocs, null);
//
//    }

    /***
     * 快车确认订单
     * @param orderId 订单id
     * @param guoluMoney 过路费
     * @param otherMoney 其他金钱
     * @param memo 备注
     * @return
     */
    @RequestMapping(value = "confirmTaskJsonFile", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport confirmTaskJsonFile(
            Long orderId,
            BigDecimal guoluMoney, BigDecimal otherMoney,
            @RequestParam(required = false, value = "memo") String memo) {

        return confirmTaskFunction(orderId, guoluMoney, otherMoney,
                memo);
    }

    private ResultTransport confirmTaskFunction(
            Long orderId,
            BigDecimal guoluMoney, BigDecimal otherMoney, String memo) {


        log.info("recv orderId:{},"
                        + "guoluMoney:{},otherMoney:{},"
                        + "memo:{}",
                orderId, guoluMoney, otherMoney, memo);


        if (null == orderId || null == guoluMoney || null == otherMoney) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        Order order = zhuancheService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        if (!order.getStatus().equals(Order.ORDER_STATUS_ARRIVE_DISTANCE)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
        }

        if (order.isTreatment()) {
            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData("waitfinish");
            return instance;
        }

        try {
            BigDecimal yuanchengMoney = null, realCash = null, startPrice = null, mileagePrice = null, runTimePrice = null, waitPrice = null;
            Double mileage = null;
            Long waitedTime = null, travelTime = null;
            //获取司机缓存, 并且把价格信息给订单对象
            DriverCache driverCache = cacheManager.getDriverCache(order.getEmployId());
            if (driverCache != null) {
                SelectPrice selectPrice = driverCache.getSelectPrice();
                if (selectPrice != null) {
                    yuanchengMoney = selectPrice.getRemoteCost();
                    realCash = selectPrice.getShouldCash().add(guoluMoney).add(otherMoney);
                    startPrice = selectPrice.getQbCost();
                    mileagePrice = selectPrice.getDisCost();
                    runTimePrice = selectPrice.getTravalTimeCost();
                    waitPrice = selectPrice.getWaitCost();
                    mileage = selectPrice.getRunKilometers();
                    waitedTime = selectPrice.getWaitSeconds();
                    travelTime = selectPrice.getTravelSeconds();
                }
            }

            order.setGuoluMoney(guoluMoney);
            order.setYuanchengMoney(yuanchengMoney);
            order.setOtherMoney(otherMoney);
            order.setRealPay(null == realCash?0.0:realCash.doubleValue());

            //优惠券
            Coupon coupon = null;
            BigDecimal coupon_hasPayed = BigDecimal.ZERO;
            Double discount = null;
            if (null != order.getCouponId()) {
                coupon = couponService.findOne(order.getCouponId());
                if (null != coupon) {
                    if (coupon.getCouponRule().getType().equals(CouponRule.TYPE_DEDUCTION)) {
                        coupon_hasPayed = coupon.getCouponRule().getMoney();
                    } else if (coupon.getCouponRule().getType().equals(CouponRule.TYPE_DISCOUNT)) {
                        discount = coupon.getCouponRule().getDiscount();
                        coupon_hasPayed = realCash.subtract(order.getGuoluMoney()).multiply(new BigDecimal(1).subtract(new BigDecimal(discount).divide(new BigDecimal(10)))).setScale(0, BigDecimal.ROUND_DOWN);
                    }
                }
            }

            order.setCouponMoney(coupon_hasPayed);
            if (coupon_hasPayed.doubleValue() > 0 && null == order.getPrePayTypeDetail()) {
                order.setPrePayTypeDetail(Order.PayTypeDetails.coupon);
            }
            order.setDiscount(discount);

            BigDecimal m = new BigDecimal(mileage);
            double df = m.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
            order.setMileage(df);
            order.setMidwayWait(waitedTime);
            order.setRunTime(travelTime);

            if (null != startPrice) {
                order.setStartPrice(startPrice.doubleValue());
            }
            if (null != mileagePrice) {
                order.setMileagePrice(mileagePrice.doubleValue());
            }
            if (null != runTimePrice) {
                order.setRunTimePrice(runTimePrice.doubleValue());
            }
            if (null != waitPrice) {
                order.setWaitPrice(waitPrice.doubleValue());
            }

//            if (StringUtils.isNotBlank(toPlace) && null != toPlaceLng && null != toPlaceLat) {
//                if (StringUtils.isBlank(order.getEndAddress())) {
//                    order.setEndLng(toPlaceLng);
//                    order.setEndLat(toPlaceLat);
//                    order.setEndAddress(toPlace);
//                }
//            }

            order.setTreatment(true);
            order.setMemo(memo);
           /* if (null != justKilometres) {
                order.setJustKilometres(justKilometres);
            }
            if (null != justMoney) {
                order.setJustMoney(justMoney);
            }*/
            Result<Order> result = zhuancheService.confirmTask(order, null);

            Passenger passenger = memberService.findOnePassenger(order.getPassengerId());
            if (StringUtils.isNotBlank(memo)) {
                passenger.setPlateNumber(memo);
                memberService.updatePassenger(passenger);
            }

            if (result.isSuccess()) {

                BigDecimal money = new BigDecimal(order.getRealPay());//还需支付的钱
                money = money.subtract(order.getGuoluMoney());
                money = money.subtract(coupon_hasPayed);
                if (money.doubleValue() < 0) {
                    money = BigDecimal.ZERO;
                }
                money = money.add(order.getGuoluMoney());

                Driver driver = driverService.findOne(order.getEmployId());
                zhuancheService.confirmTaskV4(order, driver);

//                if (money.doubleValue() <= 0) {
//                    //直接结算
//
//                    result = zhuancheService.completeTaskNewV3(order, passenger, driver, "clickComplete", null, null, Boolean.FALSE);
//                    if (result.isSuccess()) {
//                        OrderEmployHasPayEvent orderEmployHasPayEvent = new OrderEmployHasPayEvent(passenger, order.getId(), "zhuanche");
//                        applicationEventMulticaster.multicastEvent(orderEmployHasPayEvent);
//
//                        ZhuanMemberRebateEvent memberRebateEvent = new ZhuanMemberRebateEvent(passenger, order, new BigDecimal(order.getRealPay()), 1);
//                        applicationEventMulticaster.multicastEvent(memberRebateEvent);
//
//                        ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
//                        instance.setData("hasfinished");
//                        return instance;
//                    } else {
//                        ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
//                        return instance;
//                    }
//
//                } else {

                //进入确认页面

                //客户端提醒付费推送
                ZhuanOrderConfirmEvent zhuanOrderConfirmEvent = new ZhuanOrderConfirmEvent(order);
                applicationEventMulticaster.multicastEvent(zhuanOrderConfirmEvent);

                ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
                instance.setData("waitfinish");
                cacheManager.removeDriverCache(driver.getId());
                return instance;
//                }
            } else {
                ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
                return instance;
            }

        } catch (Exception e) {
            e.printStackTrace();
            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
            return instance;
        }

    }

    /**
     * 快车司机代付 乘客余额支付 订单支付
     *
     * @param orderId
     * @param payType
     * @param who
     * @return
     * @record zhyu
     */
    @RequestMapping(value = "finishTask", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport finishTask(Long orderId, String payType, String who) {

        log.info("recv orderId:{},payType{}", orderId, payType);

        if (null == orderId || StringUtils.isBlank(payType)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        if (!"helppay".equals(payType) && !"sign".equals(payType) && !"balance".equals(payType)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        Order order = zhuancheService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        if (order.getStatus().equals(Order.ORDER_STATUS_OK)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_HAS_BEEN_FINISHED);
        }

        if (!order.getStatus().equals(Order.ORDER_STATUS_ARRIVE_DISTANCE)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
        }

        if (!order.isTreatment()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_CONFIRM);
        }

        Setting setting = settingUtils.get();

        Double afterPayMoney = 0d;
        if (order.getIsMakePrice() == 1 && order.getIsMakePrice() != null) {
            afterPayMoney = Double.valueOf(String.valueOf(order.getMakePrice()));
        } else {
            if (null != order.getPrePayTypeDetail()) {
                if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon)) {
                    afterPayMoney = order.getRealPay() - order.getCouponMoney().doubleValue();
                } else {
                    afterPayMoney = order.getRealPay() - order.getBudgetPay();
                }
            } else {
                afterPayMoney = order.getRealPay();
            }
        }

        Driver driver = driverService.findOne(order.getEmployId());
        // 如果是代付，服务人员收到现金，余额减钱
        if ("helppay".equals(payType)) {
            if (afterPayMoney.doubleValue() >= 10000) {
                return ResultTransport.getErrorBy(ErrorConstantV4.HELP_PAY_MONEY_TOOLARGE);
            }
            if (null == driver) {
                return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
            }
            if (!setting.isOpenHelpPay()) {
                return ResultTransport.getErrorBy(ErrorConstantV4.NOT_ALLOW_HELP_PAY);
            }
            //$$$ 代付检测
            if (!setting.isAllowHelppayNe() && !helppayService.checkHelpMoneyEnough(driver.getId(), new BigDecimal(afterPayMoney))) {
                return ResultTransport.getErrorBy(ErrorConstantV4.HELPPAY_MONEY_NOT_ENOUGH);
            }
        }

        Passenger passenger = memberService.findOnePassenger(order.getPassengerId());
        if (null != passenger) {
            if ("sign".equals(payType)) {//签单支付
                if (passenger.getType() == Passenger.TYPE_PASSENGER) {
                    if (!passenger.isAllowOverdraw()) {
                        return ResultTransport.getErrorBy(ErrorConstantV4.PASSENGER_NOT_ALLOW_SIGN);
                    }
                } else if (passenger.getType() == Passenger.TYPE_ENTERPRISE) {
                    Enterprise enterprise = memberService.findOneEnterprise(passenger.getEnterprise_id());
                    if (!enterprise.isAllowOverdraw()) {
                        return ResultTransport.getErrorBy(ErrorConstantV4.PASSENGER_NOT_ALLOW_SIGN);
                    }
                }
            } else if ("balance".equals(payType)) {//余额支付
                if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                    BigDecimal shengyuMoney = BigDecimal.ZERO;
                    shengyuMoney = shengyuMoney.add(passenger.getNodrawMoney());
                    if (passenger.getDrawMoney().doubleValue() > 0) {
                        shengyuMoney = shengyuMoney.add(passenger.getDrawMoney());
                    }
                    if (shengyuMoney.doubleValue() < afterPayMoney) {
                        return ResultTransport.getErrorBy(ErrorConstantV4.PASSENGER_MONEY_NOT_ENOUGH);
                    }
                } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                    Enterprise enterprise = memberService.findOneEnterprise(passenger.getEnterprise_id());
                    BigDecimal shengyuMoney = BigDecimal.ZERO;
                    shengyuMoney = shengyuMoney.add(enterprise.getNodrawMoney());
                    if (enterprise.getDrawMoney().doubleValue() > 0) {
                        shengyuMoney = shengyuMoney.add(enterprise.getDrawMoney());
                    }
                    if (shengyuMoney.doubleValue() < afterPayMoney) {
                        return ResultTransport.getErrorBy(ErrorConstantV4.PASSENGER_MONEY_NOT_ENOUGH);
                    }
                }

            }
        }

        try {

            Result<Order> result = zhuancheService.completeTaskNewV3(order, passenger, driver, "clickPay", payType, null, Boolean.FALSE);

            if (result.isSuccess()) {

                if (StringUtils.isNotBlank(who) && who.equals("passenger")) {
                    OrderPassengerHasPayEvent orderPassengerHasPayEvent = new OrderPassengerHasPayEvent(driver, order.getId(), "zhuanche");
                    applicationEventMulticaster.multicastEvent(orderPassengerHasPayEvent);
                } else {
                    OrderEmployHasPayEvent orderEmployHasPayEvent = new OrderEmployHasPayEvent(passenger, order.getId(), "zhuanche");
                    applicationEventMulticaster.multicastEvent(orderEmployHasPayEvent);
                }

                ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);

                //推送至监管平台
                superviceService.pushDcyy(order, passenger, driver);


                return instance;
            } else {
                if (result.getErrorcode().equals(String.valueOf(ErrorConstantV4.ORDER_HAS_BEEN_FINISHED.getCode()))) {
                    ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.ORDER_HAS_BEEN_FINISHED);
                    return instance;
                } else {
                    ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
                    return instance;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
            return instance;
        }

    }


    /**
     * 专车接单推送
     * @param orderId
     * @return
     * @record zhyu
     */
    @RequestMapping(value = "acceptOrder")
    @Transactional(rollbackFor = Exception.class)
    public @ResponseBody
    ResultTransport acceptOrder(Long employId, Long orderId) {


        if (null == orderId || null == employId) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        Driver driver = driverService.findOne(employId);

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        Order order = zhuancheService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        try {
            Integer isBook = order.getBookStatus();
            if (driver.getStatus() != Driver.DRIVER_OFFLINE) {
                if (null == isBook || isBook.equals(0)) {
                    driverService.updateStatusAndJobStatus(Driver.DRIVER_BUSY, Driver.DRIVER_JOBSTATUS_ZHUANCHE, driver.getId());
                }
            }

            DriverCache cache = new DriverCache();
            cache.setDriverId(driver.getId());
            Area area = areaMapper.selectByPrimaryKeyWithCharge(order.getAreaId());
            SelectPrice selectPrice = new SelectPrice();
            cache.setOrderServerTime(order.getServerTime().getTime());
            selectPrice.initByArea(area, new Date(cache.getOrderServerTime()));
            cache.setSelectPrice(selectPrice);
            cache.setDriverJobStatus(driver.getJobStatus());
            cache.setOrderEndLat(order.getEndLat());
            cache.setOrderEndLng(order.getEndLng());
            cache.setDriverStatus(driver.getStatus());
            cache.setOrderStatus(order.getStatus());
            cache.setOrderId(orderId);
            cacheManager.saveOrUpdateObj(cache);
            cacheManager.putDriverCache(cache);
            ZhuanOrderAcceptEvent acceptEvent = new ZhuanOrderAcceptEvent(order, driver);
            applicationEventMulticaster.multicastEvent(acceptEvent);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);

            //推送监管平台
            superviceService.pushDdpd(order, driver);

            return instance;

        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("error", e);
            }
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }

    @RequestMapping(value = "refuseOrder")
    public @ResponseBody
    ResultTransport refuseOrder(Long orderId, Long employId, String memo) {

        if (null == orderId || null == employId || StringUtils.isBlank(memo)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        Driver driver = driverService.findOne(employId);

        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        Order order = zhuancheService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        try {

            if (driver.getStatus() != Driver.DRIVER_OFFLINE) {
                driverService.updateStatusAndJobStatus(Driver.DRIVER_ONLINE, null, driver.getId());
            }

            //拒绝工单记录
            DriverRefuseRecord driverRefuseRecord = new DriverRefuseRecord();
            driverRefuseRecord.setEmployId(driver.getId());
            driverRefuseRecord.setEmployRealName(driver.getRealname());
            driverRefuseRecord.setEmployUserName(driver.getUsername());
            driverRefuseRecord.setEmployPhone(driver.getPhone());
            driverRefuseRecord.setHappend(new Date());
            driverRefuseRecord.setOrderId(order.getId());
            driverRefuseRecord.setOrderNumber(order.getOrderNo());
            driverRefuseRecord.setOrderCompanyId(order.getCompanyId());
            driverRefuseRecord.setMemo(memo);
            driverRefuseRecord.setOrderType(DriverRefuseRecord.OrderType.zhuanche);
            driverRefuseRecordService.save(driverRefuseRecord);

            //拒单后重新推送抢单或执行自动派单
            ZhuanOrderCreateEvent createEvent = new ZhuanOrderCreateEvent(orderId, employId);
            applicationEventMulticaster.multicastEvent(createEvent);

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);

            return instance;

        } catch (Exception e) {
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }

    //专车订单销单
    @RequestMapping(value = "cancel", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport cancel(Long orderId, String cause) {

        if (null == orderId || StringUtils.isBlank(cause)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        Order order = zhuancheService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        if (!order.getStatus().equals(Order.ORDER_STATUS_NEW) && !order.getStatus().equals(Order.ORDER_STATUS_PAIDAN) && !order.getStatus().equals(Order.ORDER_STATUS_JIEDAN) && !order.getStatus()
            .equals(Order.ORDER_STATUS_ARRIVE)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
        }
        try {

            Result<Order> result = zhuancheService.cancelOrder(order, cause, order.getPassengerName(), "appCancel");

            if (result.isSuccess()) {

                ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);

                return instance;

            } else {
                return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
            }
        } catch (Exception e) {
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }

    @Autowired
    private MyCacheManager cacheManager;

    @Autowired
    private AreaMapper areaMapper;

    @Autowired
    private SmallLocationService smallLocationService;

    /**
     * 快车司机到达预约地 本接口只负责修改summer表的数据和短信 这个接口不是主要接口 除了费用,短信外, 派单逻辑外, 快车的主接口都在微信系统.
     *
     * @param orderId
     * @return
     * @record zhyu
     */
    @RequestMapping(value = "pushWaitZhuan")
    public @ResponseBody
    ResultTransport pushWaitZhuan(Long orderId) {
        if (null == orderId) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        Order order = zhuancheService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        try {
            Company orderCompany = companyService.findOne(order.getCompanyId());
            Company finalCompany = orderCompany;
            Company main = companyService.getMain();
            Setting setting = settingUtils.get();
            if (!main.getId().equals(orderCompany.getId()) && setting.isSmsMainCompany()) {
                finalCompany = main;
            }

            Integer isBook = order.getBookStatus();
            if (null != isBook && isBook > 0) {
                driverService
                    .updateStatusAndJobStatus(Driver.DRIVER_BUSY, Driver.DRIVER_JOBSTATUS_ZHUANCHE,
                        order.getEmployId());
            }
            //zhyu 缓存开始等待时间
            Driver driver = driverService.findOne(order.getEmployId());
            DriverCache cache = cacheManager.getDriverCache(driver.getId());
            if (cache != null) {
                cache.setDriverStatus(driver.getStatus());
                cache.setOrderStatus(order.getStatus());
                cache.getSelectPrice().setStartWait(System.currentTimeMillis());
                cache.getSelectPrice().setWaitSeconds(0L);
                cacheManager.saveOrUpdateObj(cache);
            }

            SmsTemplet templet = smsService.findByAlias(finalCompany.getId(), SmsType.driverAccept);
            if (templet != null && StringUtils.isNotBlank(templet.getContent())) {

                //smsService.sendSms(order.getPassengerPhone(), "arriveFromZhuanchePlace", "{\"服务人员名\":\"" + order.getEmployName() + "\",\"服务人员工号\":\"" + driver.getUsername() + "\",\"服务人员电话\":\"" + order.getEmployPhone() + "\",\"订单号\":\"" + order.getOrderNo() + "\",\"预约地\":\"" + order.getStartAddress() + "\"}", finalCompany.getId(), 0, finalCompany.getSignName());
                //短信发送（改）
                JSONObject smsParam = new JSONObject();
                smsParam.put("name",order.getEmployName());
                smsParam.put("user",driver.getUsername());
                smsParam.put("tel",order.getEmployPhone());
                smsParam.put("order",order.getOrderNo());
                smsService.sendSms(order.getPassengerPhone(),templet.getTemplateId(),smsParam.toJSONString(),finalCompany.getId(), 0, finalCompany.getSignName());
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);

            return instance;

        } catch (Exception e) {
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }

    /**
     * 快车司机开始出发接口
     *
     * @param orderId
     * @return
     * @record zhyu
     */
    @RequestMapping(value = "pushRunOrder")
    public @ResponseBody
    ResultTransport pushRunOrder(Long orderId) {
        if (null == orderId) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        Order order = zhuancheService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        Passenger passenger = memberService.findOnePassenger(order.getPassengerId());
        Driver driver = driverService.findOne(order.getEmployId());

        if (null == passenger) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PASSENGER_NOT_EXISTS);
        }

        try {

            ZhuanOrderRunEvent zhuanOrderRunEvent = new ZhuanOrderRunEvent(order, passenger);
            applicationEventMulticaster.multicastEvent(zhuanOrderRunEvent);
            DriverCache driverCache = cacheManager.getDriverCache(driver.getId());
            if (driverCache != null) {
                driverCache.setDriverJobStatus(driver.getJobStatus());
                driverCache.setOrderStatus(order.getStatus());
                driverCache.getSelectPrice().setStartRun(System.currentTimeMillis());
                driverCache.getSelectPrice().setRunKilometers(0d);
                driverCache.getSelectPrice().setTravelSeconds(0L);
                cacheManager.saveOrUpdateObj(driverCache);
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);

            superviceService.pushDcyy(order, passenger, driver);
            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
    }

    @ResponseBody
    @RequestMapping("mockComputeTask")
    public ResultTransport mockCompleteTaskData(Long orderId, @RequestParam(required = false, name = "starttime") Long start, @RequestParam(required = false, name = "endtime") Long end) {
        if (orderId == null) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }
        ResultTransport errorBy = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
        Order one = zhuancheService.findOne(orderId);
        if (one != null) {
            SelectPrice selectPrice = new SelectPrice();
            Area area = areaMapper.selectByPrimaryKeyWithCharge(one.getAreaId());
            selectPrice.initByArea(area, one.getCreated());
            List<OrderStatus> statusList = one.getStatusList();
            for (OrderStatus orderStatus : statusList) {
                if (orderStatus.getStatus().equals(Order.ORDER_STATUS_ARRIVE)) {
                    selectPrice.setStartWait(orderStatus.getCreated().getTime());
                    continue;
                } else if (orderStatus.getStatus().equals(Order.ORDER_STATUS_ZHIXING)) {
                    selectPrice.setStartRun(orderStatus.getCreated().getTime());
                    continue;
                } else if (orderStatus.getStatus().equals(Order.ORDER_STATUS_ARRIVE_DISTANCE)) {
                    selectPrice.setEndRun(orderStatus.getCreated().getTime());
                }
            }
            List<SmallLocation>  parseArray = null;
//            if (false) {
////                List<OrderLocationMany> dr = orderLocationManyMapper.selectByOrderTypeAndOrderId(OrderLocation.OrderType.zhuanche_dr, orderId);
////                List<OrderLocationMany> pa = orderLocationManyMapper.selectByOrderTypeAndOrderId(OrderLocation.OrderType.zhuanche_pa, orderId);
////                List<SmallLocation> p1 = null;
////                List<SmallLocation> d1 = null;
////                if (0 != dr.size()) {
////                    OrderLocationMany orderLocationMany1 = dr.get(0);
////                    String jsonLocs1 = orderLocationMany1.getJsonLocs();
////                    if (jsonLocs1 != null) {
////                        d1 = JSONArray.parseArray(jsonLocs1, SmallLocation.class);
////                    }
////                }
////                if (0 != pa.size()) {
////                    OrderLocationMany orderLocationMany1 = pa.get(0);
////                    String jsonLocs2 = orderLocationMany1.getJsonLocs();
////                    if (jsonLocs2 != null) {
////                        p1 = JSONArray.parseArray(jsonLocs2, SmallLocation.class);
////                    }
////                }
////                parseArray = smallLocationService.combineSmallLocations(p1, d1);
//            } else {
            List<OrderLocationMany> orderLocationManies = orderLocationManyMapper.selectByOrderTypeAndOrderId(OrderLocation.OrderType.zhuanche, orderId);
            OrderLocationMany orderLocationMany = orderLocationManies.get(0);
            String jsonLocs = orderLocationMany.getJsonLocs();
            if (jsonLocs != null) {
                parseArray = new LinkedList<>(JSONArray.parseArray(jsonLocs, SmallLocation.class));
            }
            if (null != start) {
                parseArray = parseArray.stream().filter(o -> o.getLocDate() >= start && o.getLocDate() <= end).collect(Collectors.toList());
            }
            if (null != parseArray && 2 > parseArray.size()) {
                addStartAndEnd(one, selectPrice, parseArray);
            }
            Double miles = smallLocationService.filterAndComputeMiles(parseArray, true, orderId);
            if (miles != null) {
                Double kilo = miles / 1000;
                selectPrice.setRunKilometers(kilo);
                boolean b = selectPrice.freshPrice(Order.ORDER_STATUS_ARRIVE_DISTANCE, true);
                errorBy.setData(selectPrice);
            }
        }
        return errorBy;
    }

    /**
     * 为地理点添加订单的开始和结束地点
     *
     * @param one
     * @param selectPrice
     * @param parseArray
     */
    public void addStartAndEnd(Order one, SelectPrice selectPrice, List<SmallLocation> parseArray) {
        LinkedList<SmallLocation> link = new LinkedList<>(parseArray);
        SmallLocation f = new SmallLocation();
        f.setLocDate(selectPrice.getStartRun());
        f.setLongitude(one.getStartLng());
        f.setLatitude(one.getStartLat());
        SmallLocation e = new SmallLocation();
        e.setLocDate(selectPrice.getEndRun());
        e.setLongitude(one.getEndLng());
        e.setLatitude(one.getEndLat());
        link.addFirst(f);
        link.addLast(e);
        parseArray = link;
        if (locationLogger.isInfoEnabled()) {
            locationLogger.info("add start and end");
        }
    }


    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            list.add(i);
        }
        List<Integer> collect = list.stream().filter(i -> i > 2).collect(Collectors.toList());
        System.out.println(collect);
    }

    @Autowired
    private OrderLocationManyMapper orderLocationManyMapper;

    /***
     * 司机端获取快车的实时预估价格 获取快车的即时预估价格 H5获取快车预估价格 app获取快车预估价格 乘客端获取快车预估价格 获取司机地理位置信息
     * @param driverId
     * @param kiloMeters
     * @param areaId
     * @param runSeconds
     * @param waitSeconds
     * @param timestamp
     * @param debugger
     * @param orderId
     * @return
     * @record zhyu
     */
    @CrossOrigin("*")
    @RequestMapping(value = "getKuaiPrice", method = RequestMethod.GET)
    public @ResponseBody
    ResultTransport getZhuanPrice(@RequestParam(required = false) Long
        driverId, @RequestParam(required = false) Double kiloMeters, @RequestParam(required = false) Long areaId,
        @RequestParam(required = false) Long runSeconds, @RequestParam(required = false) Long
        waitSeconds, @RequestParam(required = false) Long timestamp,
        @RequestParam(required = false) Boolean debugger, @RequestParam(required = false) Long orderId) {
        SelectPrice selectPrice = null;
        ResultTransport instance;
        try {
            Map<String, Object> re = new HashMap<>(4);
            if (null != driverId) {
                DriverCache driverCache = cacheManager.getDriverCache(driverId);
                Map<String, Object> driverRe = new HashMap(3);
                if (driverCache != null) {
                    selectPrice = driverCache.getSelectPrice();
                    if (selectPrice != null) {
                        smallLocationService.freshSelectPrice(driverCache);
                        Double latitude = driverCache.getDriverLat();
                        Double longitude = driverCache.getDriverLng();
                        driverRe.put("longitude", longitude);
                        driverRe.put("latitude", latitude);
                    }
                    driverRe.put("orderId", orderId);
                    re.put("driver", driverRe);
                }
            } else if (null != kiloMeters && null != runSeconds && null != waitSeconds) {
                selectPrice = new SelectPrice();
                Area area = areaMapper.selectByPrimaryKeyWithCharge(areaId);
                timestamp = null == timestamp ? System.currentTimeMillis() : timestamp;
                waitSeconds = null == waitSeconds ? 0L : waitSeconds;
                selectPrice.computePrice(-1, runSeconds, waitSeconds, kiloMeters, area, new Date(timestamp));
            } else if (debugger && null != orderId) {

                Order order = zhuancheService.findOne(orderId);
                if (order != null) {
                    List<OrderStatus> statusList = order.getStatusList();
                    Long orderCreated = order.getCreated().getTime();
                    Long startWait = null, startRun = null, endRun = null;
                    Area area = areaMapper.selectByPrimaryKeyWithCharge(areaId);
                    if (null != statusList && 0 != statusList.size()) {
                        for (OrderStatus orderStatus : statusList) {
                            if (orderStatus.getStatus().equals(Order.ORDER_STATUS_ARRIVE)) {
                                startWait = orderStatus.getCreated().getTime();
                            } else if (orderStatus.getStatus().equals(Order.ORDER_STATUS_ZHIXING)) {
                                startRun = orderStatus.getCreated().getTime();
                            } else if (orderStatus.getStatus().equals(Order.ORDER_STATUS_ARRIVE_DISTANCE)) {
                                endRun = orderStatus.getCreated().getTime();
                            }
                        }
                    }
                }
            } else {
                return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
            }
            instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            if (selectPrice != null) {
                re.put("price", selectPrice);
                if (Boolean.TRUE.equals(debugger)) {
                    re.put("debugger", selectPrice.getPrice());
                }
            }
            instance.setData(re);
        } catch (Exception e) {
            e.printStackTrace();
            instance = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }
        return instance;
    }

    @Autowired
    private DriverLoginService driverLoginService;

//    /***
//     *
//     * @param employToken 司机token
//     * @param remoteCost 远程费
//     * @param priceTime 计价规则采用时间点
//     * @param waitSeconds   等待的秒数
//     * @param runKilometers 运行的里程数
//     * @param qbCost    起步价
//     * @param waitCost 等待价
//     * @param travalTimeCost 时间价
//     * @param disCost 里程价
//     * @param travelSeconds 行驶时间秒数
//     * @param shouldCash 总价
//     * @param uploadTime 上传时间
//     * @return
//     */
//    @ResponseBody
//    @RequestMapping(value = "uploadKuaiPrice", method = RequestMethod.POST)
//    public ResultTransport employeUploadKuaiPrice(String employToken, Double remoteCost, Long priceTime, Long waitSeconds,
//                                                  Double runKilometers, Double qbCost, Double waitCost, Double travalTimeCost,
//                                                  Double disCost, Long travelSeconds, Double shouldCash, Long uploadTime) {
//
//
//        if (StringUtils.isBlank(employToken)) {
//            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
//        }
//
//        DriverLogin driverLogin = driverLoginService.selectByToken(employToken);
//
//        if (null == driverLogin) {
//            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_ERROR);
//        }
//
//        if (System.currentTimeMillis() >= driverLogin.getDeathDate().getTime()) {
//            return ResultTransport.getErrorBy(ErrorConstantV4.TOKEN_TIME_ERROR);
//        }
//
//        Driver driver = driverService.findOne(driverLogin.getDriverId());
//
//        if (null == driver) {
//            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
//        }
//
//        DriverCache driverCache = cacheManager.getDriverCache(driver.getId());
//        if (driverCache != null) {
//            if (driverCache.getOrderStatus() != Order.ORDER_STATUS_ZHIXING || null != driverCache.getEndRunTime())
//                return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
////            driverCache.setSelectPrice(selectPrice);
//            cacheManager.saveOrUpdateObj(driverCache);
//        } else {
//            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_HAS_NOT_ACCEPT_ORDER);
//        }
//        return ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
//    }

    private Logger locationLogger = LoggerFactory.getLogger("location");

    @ResponseBody
    @CrossOrigin("*")
    @RequestMapping(value = "passengerUploadLocation", method = RequestMethod.POST)
    public ResultTransport passengerUploadLocation
            (Long driverId, Integer id,
             Double longitude, // 经度
             Double latitude, // 纬度
             @RequestParam(required = false) Double direction,
             Long locDate,
             @RequestParam(required = false) String locType,
             @RequestParam(required = false) String orderIds,
             @RequestParam(required = false) String orderType,
             @RequestParam(required = false) Double radius,
             @RequestParam(required = false) Integer run) {

        if (null == driverId || null == longitude || null == latitude || null == locDate) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }
        SmallLocation smallLocation = new SmallLocation();
        smallLocation.setLocDate(locDate);
        smallLocation.setLatitude(latitude);
        smallLocation.setLongitude(longitude);
        if (locationLogger.isDebugEnabled()) {
            locationLogger.debug("pa {} {}", driverId, smallLocation);
        }
        DriverCache driverCache = cacheManager.getDriverCache(driverId);
        if (driverCache != null) {
            if (!driverCache.getOrderStatus().equals(Order.ORDER_STATUS_ZHIXING)) {
                return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
            }
            driverCache.putPassengerLocation(smallLocation);
//            if (lastedPassengerLocation != null) {
//                if (smallLocationService.isTheSameLocation(smallLocation, lastedPassengerLocation) || null != driverCache.getEndRunTime())
//                    return ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
//            }
//            smallLocationService.synComputeMileAndComputePrice(smallLocation, driverCache);
            cacheManager.saveOrUpdateObj(driverCache);
        } else {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_HAS_NOT_ACCEPT_ORDER);
        }
        return ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
    }
//	public static void main(String[] args) {
//        System.out.println(new Date());
//		System.out.println(new BigDecimal("3.44").setScale(1, BigDecimal.ROUND_HALF_DOWN).doubleValue());
//		System.out.println(new BigDecimal("3.45").setScale(1, BigDecimal.ROUND_HALF_DOWN).doubleValue());
//		System.out.println(new BigDecimal("3.46").setScale(1, BigDecimal.ROUND_HALF_DOWN).doubleValue());
//
//		System.out.println("---------------");
//		System.out.println(new BigDecimal("3.44").setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue());
//		System.out.println(new BigDecimal("3.45").setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue());
//		System.out.println(new BigDecimal("3.46123213").setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue());
//	}

    private SelectPrice getComputePriceFromlocFileByOrderId() {
        return null;
    }
}
